<template>
  <div class="container" v-if="finish">
    <Navbar title="个人中心"></Navbar>
    <div class="user-avatar">
      <img :src="user.avatar" alt="">
      <span>点击更换头像</span>
      <input type="file" @change="modify($event)">
    </div>
    <h2>账户信息</h2>
    <van-cell-group :border="false">
      <van-cell title="昵称" is-link :value="user.nick_name" @click="setName"/>
      <van-cell title="绑定手机号" is-link :value="user.mobile.replace(/(\d{3})\d{4}(\d{4})/,'$1****$2')" />
      <van-cell title="修改密码" is-link value="设置密码" />
    </van-cell-group>
  </div>
</template>

<script>
import Navbar from '@/components/common/Navbar';
import { getUser, updateAvatar } from '@/network/member';
import { Notify } from 'vant';

export default {
  components: {
    Navbar,
  },
  data() {
    return {
      finish: false,
      user: {},
    };
  },
  methods: {
    modify(e) {
      const formData = new FormData();
      const files = e.target.files[0];
      const fileType = files.type.split('/')[1];
      if (fileType != 'png' && fileType && 'jpg' && fileType != 'jpeg') return Notify('图片格式错误,请上传png/jpg/jpeg格式的图片');
      formData.append('file', files);
      updateAvatar(formData).then((res) => {
        if (res.code == 0) {
          Notify({ type: 'success', message: '上传头像成功' });
        }
      });
    },
    setName() {
      if (this.user.nick_name) return Notify('您已经设置过昵称了哦');
    },
  },
  created() {
    getUser().then((res) => {
      this.user = res.data;
      this.finish = true;
    });
  },
};
</script>

<style lang="less" scoped>
.user-avatar {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 28px 0;
  img {
    width: 64px;
    height: 64px;
    border-radius: 50%;
  }
  span {
    font-size: 12px;
    margin-top: 8px;
  }
  input {
    position: absolute;
    opacity: 0;
    width: 64px;
    height: 64px;
  }
}
h2 {
  font-size: 16px;
  padding: 6px 16px;
}
</style>
